package com.yds.developtools.utils

import android.os.Handler
import android.os.Looper
import java.lang.ref.WeakReference

/**
 * 作者:     YDS
 * 创建时间: 2024/11/17 10:49
 * 页面描述: 延时帮助类
 */
object YDSDelayHelper {

    private val mHandler = Handler(Looper.getMainLooper())

    // 使用WeakReference来存储Runnable，避免强引用导致无法自动回收
    private var runnableWeakRef: WeakReference<Runnable>? = null

    fun delay(delayMillis: Long, action: () -> Unit) {
        val runnable = Runnable {
            action()
            runnableWeakRef = null
        }
        runnableWeakRef = WeakReference(runnable)
        runnableWeakRef?.get()?.let {
            mHandler.postDelayed(it, delayMillis)
        }
    }

    fun destroy() {
        runnableWeakRef?.get()?.let { mHandler.removeCallbacks(it) }
    }
}